<script>
import { needRequestToken, cryptoToken } from './utils/auth'
import MPRequest from './utils/request'

export default {
  onLaunch () {
    // 小程序启动程序
    console.log('Lanuch APP')
    cryptoToken('123')
    console.log('cryptoToken APP')
    // 获取设备布局信息
    mpvue.setStorageSync(
      'menuButtonObject',
      wx.getMenuButtonBoundingClientRect()
    )
    wx.getSystemInfo({
      success: data => {
        mpvue.setStorageSync('systemData', data)
      }
    })
    MPRequest.beforeAction().then(token => {
      console.log('启动页面的前置操作')
    })
    // 判断请求token是否过期
    needRequestToken()
  },
  created () {
    // 调用API从本地缓存中获取数据
    /*
     * 平台 api 差异的处理方式:  api 方法统一挂载到 mpvue 名称空间, 平台判断通过 mpvuePlatform 特征字符串
     * 微信：mpvue === wx, mpvuePlatform === 'wx'
     * 头条：mpvue === tt, mpvuePlatform === 'tt'
     * 百度：mpvue === swan, mpvuePlatform === 'swan'
     * 支付宝(蚂蚁)：mpvue === my, mpvuePlatform === 'my'
     */
    // const that = this
    // 主要是为了获取code
    wx.login({
      success (res) {
        if (res.code) {
          // 封装的缓存方法
          mpvue.setStorageSync('code', res.code)
          console.log('----获取微信授权Code', res)
        } else {
          console.log('微信登录Code获取失败:' + res.errMsg)
        }
      }
    })
    // 获取用户当前的授权状态。本项目里判断用户是否已授权登录
    wx.getSetting({
      success (res) {
        console.log('用户信息内容：', res)
        let authSetting = res.authSetting
        if (authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: (res) => {
              console.log(res)
              // 如果用户已经授权则会调用该方法
              // that.onAuthorize(res)
            }
          })
        } else {
          console.error('用户没有授权，发起授权')
          wx.authorize({
            scope: 'scope.userInfo',
            success (res) {
              console.error('用户已经同意授权', res)
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              // wx.startRecord()
            }
          })
          // wx.openSetting({
          //   success (res) {
          //     console.log('用户同意授权：', res.authSetting)
          // res.authSetting = {
          //   "scope.userInfo": true,
          //   "scope.userLocation": true
          // }
          //   }
          // })
        }
      }
    })

    // 日志
    let logs
    if (mpvuePlatform === 'my') {
      logs = mpvue.getStorageSync({ key: 'logs' }).data || []
      logs.unshift(Date.now())
      mpvue.setStorageSync({
        key: 'logs',
        data: logs
      })
    } else {
      logs = mpvue.getStorageSync('logs') || []
      logs.unshift(Date.now())
      mpvue.setStorageSync('logs', logs)
    }
  },
  methods: {
    // 从后台获取openid等参数信息
    onAuthorize (data) {
      return new Promise((resolve, reject) => {
        if (!mpvue.getStorageSync('userInfo').openid) {
          wx.request({
            url: 'https://mp.youmbe.com/passport/authorize',
            method: 'POST',
            data: {
              encryptedData: data.encryptedData,
              code: mpvue.getStorageSync('code'),
              iv: data.iv
            },
            success: function (info) {
              let userInfo = data.userInfo

              resolve(userInfo)
            },
            fail (res) {
              reject(res)
            }
          })
        } else {
          resolve(mpvue.getStorageSync('userInfo'))
        }
      })
    },
    // 获取数据方法
    onLogin (code) {
      console.log('test onlogin')
      const that = this
      wx.request({
        method: 'post',
        url: 'https://mp.youmbe.com/passport/authorize',
        data: {
          code: code // 传递页码
        },
        header: {
          'content-type': 'application/json'
        },
        success (res) {
          // 关闭下拉刷新动画
          wx.stopPullDownRefresh()
          // 返回的数据
          const data = res.data.data

          let itemCount = data.items.length
          if (itemCount > 0) {
            if (that.page > 1) {
              that.list.push(...data.items)
            } else {
              that.list = data.items
            }
          }
          that.meta = data.meta
        }
      })
    }
  },
  log () {
    console.log(`log at:${Date.now()}`)
  }
}
</script>

<style lang="less">
* {
  transition: width 2s;
  -moz-transition: width 2s;
  -webkit-transition: width 2s;
  -o-transition: width 2s;
  box-sizing: border-box;
}
</style>
